package me.shiqiang.im.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.corundumstudio.socketio.SocketIOClient;
import me.shiqiang.im.common.ConnectionServer;
import me.shiqiang.im.common.SocketClientMap;
import me.shiqiang.im.enums.MessageCType;
import me.shiqiang.im.msg.MsgBody;
import me.shiqiang.im.service.MsgService;
import me.shiqiang.im.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author cuishiqiang
 * @date 2017/12/16 下午3:04
 */
@Component(MessageCType.P2P)
public class P2pMsgListener implements MsgListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MsgService service;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        String s = new String(message.getBody());
        try {
            logger.info("p2p收到消息{}", s);
            MsgBody msgBody = JsonUtils.getInstance().fromJson(s, MsgBody.class);
            Long userId = Long.parseLong(message.getUserProperties("to"));
            Long syncKey = Long.parseLong(message.getUserProperties("syncKey"));
            Map<String, ConnectionServer> connectionServerMap = SocketClientMap.getInstance().connectionServerMap;
            logger.info("p2p的connectionServerMap的size{}", connectionServerMap.size());
            String serverId = service.getServerId(String.valueOf(userId));
            ConnectionServer connectionServer = connectionServerMap.get(serverId);
            SocketIOClient processor = connectionServer.nextProcessor();

            processor.sendEvent("p2pMsg",msgBody);
            logger.info("群消息发送:serverId{},machineId{}",processor.get("serverId"),processor.get("machineId"));

            return Action.CommitMessage;
        } catch (Exception e) {
            logger.error(String.format("消息处理失败：%s", s), e);
            return Action.ReconsumeLater;
        }
    }
}
